package controller;


import java.io.File;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;

import javax.net.ssl.HttpsURLConnection;

import org.jdom.*;
import org.jdom.input.SAXBuilder;


public class BestlistManager
{
	
	private String user;
	private String pwd;
	
	private String sessionid;
	
	public BestlistManager(String user, String pwd)
	{
		this.user = user;
		this.pwd = pwd;
	}
	
	public int login()
	{
		
		//TODO
		String loginAnswer = "<gympulanloginaction><status>loginSuccess</status><gplsession>1234ABCD</gplsession></gympulanloginaction>";// XML-Doc
		
		Document doc = String2XML(loginAnswer);
		if (doc == null)
		{
			return 1;
		}
		
		if (doc.getRootElement().getChildText("status").equals("loginSuccess"))
		{
			//login erfolgreich
			this.sessionid = doc.getRootElement().getChildText("gplsession");
			return 0;
		}
		else if (doc.getRootElement().getChildText("status").equals("loginFailed"))
		{
			return 2;
		}
		else if (doc.getRootElement().getChildText("status").equals("secureCodeFail"))
		{
			return 3;
		}
		else if (doc.getRootElement().getChildText("status").equals("toomanyattempts"))
		{
			return 4;
		}
		return 5;
	}
	
	public BestlistEntry[] getBestenliste(int start, int end)
	{
		if (login() != 0)
		{
			return null;
		}
		
		//TODO
		String bestlist = "";
		
		Document doc = String2XML(bestlist);
		
		if (doc.getRootElement().getChildText("status").equals("gplsessionovertime"))
		{
			if (login() != 0)
			{
				return null;
			}
		}

		ArrayList<BestlistEntry> list = new ArrayList<BestlistEntry>();
		
		while (doc.getRootElement().getChild("bestlistentry") != null)
		{
			Element e = doc.getRootElement().getChild("bestlistentry");
			list.add(new BestlistEntry(Integer.parseInt(e.getChildText("position")), e.getChildText("displayname"), Integer.parseInt(e.getChildText("points"))));
			doc.getRootElement().removeChild("bestlistentry");	
		}
		
		return list.toArray(new BestlistEntry[list.size()]);
		
	}
	
	public int postHighscore(double score)
	{
		//TODO

		//entferen (Debug):
		System.out.println("Debuginfo: BestListManager-Post: user=" + user + "; pwd=" + pwd + "; score=" + score);
		
		String postAnswer = "<hallo/>";
		
		Document doc = String2XML(postAnswer);
		
		try
		{
			if (doc == null)
			{
				return -1;
			}
			else if (doc.getRootElement().getChildText("status").equals("nosuccess"))
			{
				return -2;
			}
			else if (doc.getRootElement().getChildText("status").equals("success"))
			{
				return Integer.parseInt(doc.getRootElement().getChildText("position"));
			}
		}
		catch (NullPointerException e)
		{
			e.printStackTrace();
			return -3;
		}
		
		return -4;
	}
	
	
	/**
	 * Lädt eine Datei aus dem Internet herunter und speichert sie in einem String
	 * @param url Die URL zu der Datei
	 * @since 0.1
	 * @return Den Inhalt der Datei, bei Fehlern wird ein leerer String zurückgegeben
	 */
	static private String httpsDownload2String(String url)
	{
		try
		{
			URL Url = new URL(url);
			HttpsURLConnection c = (HttpsURLConnection) Url.openConnection();
			c.setUseCaches(false);
			InputStreamReader input = new InputStreamReader(c.getInputStream());
			String response = "";
			int x = input.read();
			while (x != -1)
			{
				response += (char) x;
				x = input.read();
			}
			input.close();
			return response;
		}
		catch (Exception e)
		{
			return "";
		}
	}
	
	private static Document String2XML(String s)
	{
		SAXBuilder builder = new SAXBuilder();
		Document doc;
		try
		{
			doc = builder.build(new StringReader(s));
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		return doc;
	}

	public static Document File2XML(String path)
	{
		SAXBuilder builder = new SAXBuilder();
		Document doc;
		try
		{
			doc = builder.build(new File(path));
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		return doc;
	}
	
}
